package com.xxx.servlet;

import com.alibaba.fastjson.JSON;
import com.xxx.pojo.Package;
import com.xxx.pojo.PageTools;
import com.xxx.service.Services;
import com.xxx.service.impl.PackageServiceImpl;
import com.xxx.util.GetIdTime;
import com.xxx.util.JsonSwitchUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.List;

@WebServlet(urlPatterns = "/package/*")
@MultipartConfig
public class PackageServlet extends BaseServlet{

    private Services services = new PackageServiceImpl();
    private Long id;

    //增

    /**
     * 套餐信息添加
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Package aPackage = JSON.parseObject(line, Package.class);
        String dataTime = GetIdTime.getDataTime();
        aPackage.setCreateTime(dataTime);
        aPackage.setUpdateTime(dataTime);
        aPackage.setUpdateUser(this.id);
        aPackage.setCreateUser(this.id);
        int i = services.add(aPackage);
        JsonSwitchUtil.toJsonString(req,resp,i>=1);
    }


    /**
     * 图片上传
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Part upload = req.getPart("upload");
        if (upload.getSize() == 0){
            return;
        }
        String name = upload.getSubmittedFileName();
        int index = name.lastIndexOf(".");
        String substring = name.substring(index);
        String fileName = GetIdTime.getId() + substring;
//        System.out.println(fileName);

        try (
                InputStream inputStream = upload.getInputStream();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\src\\main\\webapp\\img\\" + fileName));
                BufferedOutputStream bosToTarget = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\target\\LS03_vuejs\\img\\" + fileName));
        ) {
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bosToTarget.write(bytes, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取图片地址
        //绝对地址
        StringBuffer requestURL = req.getRequestURL();
        //项目相对地址
        String uri = req.getRequestURI();
        int indexOf = requestURL.lastIndexOf(uri);
//        req.getContextPath() 项目名称
        String imgPath = requestURL.substring(0, indexOf) + req.getContextPath() + "/img/";
//        System.out.println(imgPath);
        JsonSwitchUtil.toJsonString(req,resp,imgPath + fileName);

    }

    //删

    /**
     * 根据编码删除
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void deleteByCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();

        Package[] aPackages = JSON.parseObject(line, Package[].class);

        int delete = 0;

        for (Package aPackage : aPackages) {

            delete += services.delete(aPackage.getCode());
        }

        JsonSwitchUtil.toJsonString(req,resp,delete>=1);


    }

    //改

    /**
     * 根据编码修改
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void updateByCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();

        Package[] packages = JSON.parseObject(line, Package[].class);
        int i = 0;
        for (Package aPackage : packages) {
            aPackage.setUpdateUser(this.id);
            aPackage.setUpdateTime(GetIdTime.getDataTime());
            i += services.updateById(aPackage);
        }

        JsonSwitchUtil.toJsonString(req,resp,i>0);
    }
    //查

    /**
     * 查询单个页面所需数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        req.setCharacterEncoding("utf-8");

        id = (Long) req.getSession().getAttribute("id");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        PageTools pageTools = JSON.parseObject(line, PageTools.class);
        List list = services.selectAll((pageTools.getPageNo() - 1) * pageTools.getPageSize(), pageTools.getPageSize());
        JsonSwitchUtil.toJsonString(req,resp,list);

    }

    /**
     * 查询套餐种类
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectAllByTypesName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List list = services.selectAllByTypesName();
        JsonSwitchUtil.toJsonString(req,resp,list);
    }

    /**
     * 数据条目数量
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int count = services.selectCount();
        JsonSwitchUtil.toJsonString(req,resp,count);
    }

    /**
     * 根据名称查询
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
//        System.out.println(line);
        Package aPackage = JSON.parseObject(line, Package.class);
//        System.out.println(aPackage);
        Package p = (Package) services.selectByUsername(aPackage.getName());
        System.out.println(p);
        JsonSwitchUtil.toJsonString(req,resp,p == null? null:p);
    }

}
